package com.d09cnpm2.group8.map;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

public class MapV2Activity extends Activity implements LocationListener {
     LatLng currentPosition;
    private GoogleMap map;
    private String provider;
    private String TAG;
    private LocationManager locationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.mapv2layout);
	map = ((MapFragment) getFragmentManager().findFragmentById(
		R.id.map_fragment)).getMap();
	// Move the camera instantly to hamburg with a zoom of 15.
	locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
	if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
	    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
	    startActivity(intent);
	}
	if (!isNetworkAvailable()) {
	    showAlertDialog("please enable your network");
	    return;
	}
	displayCurrentLocation();
	double lat = getIntent()
		.getDoubleExtra("lat", currentPosition.latitude);
	double lng = getIntent().getDoubleExtra("lng",
		currentPosition.longitude);
	LatLng destination = new LatLng(lat, lng);
	// ---------mark destination location----------------
	 Marker maker = map.addMarker(new MarkerOptions()
	 .position(destination)
	 .title("destination")
	 .icon(BitmapDescriptorFactory
	 .fromResource(R.drawable.marker)));
	 map.moveCamera(CameraUpdateFactory.newLatLngZoom(destination, 15));
	 Toast.makeText(this, "LatLng : " + lat + " ; " + lng, Toast.LENGTH_LONG).show();
	 //--------------find direction to destination ----------------------
	 findDirection(currentPosition, destination,GMapV2Direction.MODE_WALKING);
    }

    private void showAlertDialog(String string) {
	AlertDialog dialog;
	AlertDialog.Builder builder = new AlertDialog.Builder(this);
	builder.setMessage(string).setNegativeButton("OK",
		new OnClickListener() {
		    @Override
		    public void onClick(DialogInterface dialog, int which) {
			dialog.dismiss();
		    }
		});
	dialog = builder.create();
	dialog.show();
    }

    private boolean isNetworkAvailable() {
	ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	NetworkInfo activeNetworkInfo = connectivityManager
		.getActiveNetworkInfo();
	return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    public void findDirection(LatLng currentPosition, LatLng desPosition,
	    String mode) {
	Map<String, String> map = new HashMap<String, String>();
	map.put(GetDirectionAsyncTask.CUR_LAT,
		String.valueOf(currentPosition.latitude));
	map.put(GetDirectionAsyncTask.CUR_LNG,
		String.valueOf(currentPosition.longitude));
	map.put(GetDirectionAsyncTask.DES_LAT,
		String.valueOf(desPosition.latitude));
	map.put(GetDirectionAsyncTask.DES_LNG,
		String.valueOf(desPosition.longitude));
	map.put(GetDirectionAsyncTask.DIRECTION_MODE, mode);
	// Log.e(TAG, "locations dest : " +)
	GetDirectionAsyncTask asyncTask = new GetDirectionAsyncTask(this);
	asyncTask.execute(map);
    }

    private void displayCurrentLocation() {
	map.setMyLocationEnabled(true);
	Criteria criteria = new Criteria();
	provider = locationManager.getBestProvider(criteria, false);
	Location location = locationManager.getLastKnownLocation(provider);
	if (location != null) {
	    onLocationChanged(location);
	}
	locationManager.requestLocationUpdates(provider, 2000, 0, this);
	currentPosition = new LatLng(location.getLatitude(),
		location.getLongitude());
    }

    // ----------------------------draw points on route to
    // destination-----------------
    public void drawRoutes(ArrayList<LatLng> directionPoints) {
	if (directionPoints == null)
	    return;
	Polyline newPolyline;
	PolylineOptions rectLine = new PolylineOptions().width(5).color(
		Color.RED);

	for (int i = 0; i < directionPoints.size(); i++) {
	    rectLine.add(directionPoints.get(i));
	}
	newPolyline = map.addPolyline(rectLine);
    }

    @Override
    public void onLocationChanged(Location arg0) {
	// TODO Auto-generated method stub

    }

    @Override
    public void onProviderDisabled(String arg0) {
	// TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String arg0) {
	// TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
	// TODO Auto-generated method stub

    }

}
